import {
	BASE_URL
} from './baseurl.js'

export const request = (url, method = 'GET', data = {}, header = {}, isloading = true) => {
	if (isloading) {
		wx.showLoading({
			title: '加载中...'
		})
	}

	return new Promise(async (resolve, reject) => {
		header["token"] = await uni.getStorageSync("token") || '';

		let requestUrl = BASE_URL + url;
		if (method === 'GET' && data) {
			// 如果是 GET 请求且有参数，手动拼接参数到 URL 上
			let paramsStr = '';
			for (const key in data) {
				if (data.hasOwnProperty(key)) {
					paramsStr += `${paramsStr? '&' : ''}${key}=${encodeURIComponent(data[key])}`;
				}
			}
			requestUrl += `?${paramsStr}`;
		}
		uni.request({
			url: requestUrl,
			method: method,
			data: method === 'GET' ? {} : data,
			header: header,
			success: (res) => {
				if (res.data.code == 401) {
					uni.removeStorageSync('token');
					uni.showModal({
						title: '温馨提示',
						content: '登录后才可以操作',
						confirmText: '去登录',
						cancelText: "我知道了",
						confirmColor: "#e43927",
						success: async (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/loginMain/loginMain'
								})
							}
						}
					});
				} else if (res.data.code == 500) {
					uni.showToast({
						title: '服务器资源异常',
						icon: 'none',
						duration:1500
					})
					reject(res.data)
				} else if (res.data.code == 0) {
					uni.showToast({
						title: res.data.msg || '系统繁忙',
						icon: 'none',
						duration:1500
					})
					reject(res.data)
				}
				resolve(res.data)
			},
			fail: (err) => {
				let result = {
					code: 500,
					msg: "获取数据失败",
					duration:1500
				};
				reject(result)
			},
			complete() {
				if (isloading) wx.hideLoading()
			}
		})
	})
}

export const form = (url, param) => {
	return request(url, "post", param, {
		'Content-Type': 'application/x-www-form-urlencoded'
	})
}

export const post = (url, param) => {
	return request(url, "post", param, {
		'Content-Type': 'application/json'
	})
}

export const loadPostData = (url, param, ref) => {
	let res = post(url, param);
	res.then((res) => {
		if (res.code !== 200) {
			return;
		}
		ref.value = res.data || [];
	}).catch((err) => {
		console.log(err);
	})
}

export const loadPostCallback = (url, param, callback) => {
	let res = post(url, param);
	res.then((res) => {
		if (res.code !== 200) {
			return;
		}
		if (callback) {
			callback(res);
		}
	}).catch((err) => {
		console.log(err);
	})
}

//上传图片
export const uploadf = (e) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: BASE_URL,
			header: {
				token: uni.getStorageSync('token')
			},
			filePath: e,
			name: 'file',
			success: val => {
				resolve(val)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}